package blms.system;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import blms.system.exception.CreationException;
import blms.system.exception.InexistentUserException;
import blms.system.exception.UnknownUserAttribute;
import blms.system.factory.UserFactory;
import blms.system.util.Validator;

public class BLMS {
	
	private Map<String, User> users;
	private UserFactory factory;
	private Validator validator; 
	
	
	public BLMS() {
		this.users = new HashMap<String, User>();
		this.factory = new UserFactory();
		this.validator = new Validator();
	}

	public String createUser(String firstName, String lastName, String homePhone,
			String workPhone, String cellPhone, String email, File picture) throws CreationException {
		
		if (this.users.keySet().contains(email)) throw new CreationException("User with this email exists");
		
		validator.validate(firstName,lastName,email,homePhone,workPhone,cellPhone);
		
		User user = factory.createUser(firstName, lastName, homePhone, workPhone, cellPhone, email, picture);
		
		this.users.put(user.getID(), user);
		return user.getID();
	}

	public String getUserAttribute(String id, String attribute) throws InexistentUserException, UnknownUserAttribute {
		User user = this.getUser(id);
		UserAttributes att = UserAttributes.translateAttribute(attribute);
		return user.getAttribute(att);
	}

	private User getUser(String id) throws InexistentUserException {
		User user = this.users.get(id);
		
		if (user == null) throw new InexistentUserException();
		return user;
	}

	public void changeUserAttribute(String id, String attribute, String value) throws InexistentUserException, UnknownUserAttribute {
		User user = this.getUser(id);
			
		if (this.validator.isBlankOrNull(attribute)) throw new IllegalArgumentException("Must provide an attribute to be changed");
		
		UserAttributes att = null;
		att = UserAttributes.translateAttribute(attribute);

		if (this.validator.isBlankOrNull(value) && UserAttributes.isMandatory(attribute)) throw new IllegalArgumentException("Required data: " + att);
					
		user.changeAttribute(att, value);
	}
}
